<template>
  <div>
    <el-backtop></el-backtop>
    <el-table :data="tableData" style="width: 100%" highlight-current-row>
      <el-table-column type="index" label="Id" width="50"></el-table-column>
      <el-table-column label="字节" width="400">
        <template slot-scope="scope">
          <el-row
            :gutter="20"
            v-for="(item, ind) in scope.row.tt.child"
            :key="ind + 2"
          >
            <el-col :span="5">
              <el-image
                style="width: 70px; height: 70px"
                :src="item.product_pic"
                fit="fit"
              ></el-image>
            </el-col>
            <el-col :span="15">
              <el-row
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
                :title="item.product_name"
                >标题：{{ item.product_name }}</el-row
              >
              <el-row>
                <span v-for="(item, index) in item.spec_desc" :key="index">
                  {{ item.name }}:
                  {{ item.value }}
                </span>
              </el-row>
              <el-row>店铺：{{ scope.row.tt.shopId }}</el-row>
              <el-row>子订单数量：{{ scope.row.tt.childNum }}</el-row>
              <el-row>子订单sku的数量：{{ item.combo_num }}</el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="1688" width="400">
        <template slot-scope="scope">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-image
                style="width: 70px; height: 70px"
                :src="scope.row.ali.image.images[0]"
                fit="fit"
                :preview-src-list="scope.row.ali.image.images"
              ></el-image>
            </el-col>
            <el-col :span="15">
              <el-row
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
                :title="scope.row.ali.subject"
                >标题：{{ scope.row.ali.subject }}</el-row
              >
              <el-row style="border: 1px dashed #2aa1ff" title="修改">
                <el-badge value="修改" class="item" type="primary">
                  <el-link
                    :underline="false"
                    @click="scope.row.fixEdu = !scope.row.fixEdu"
                    v-show="!scope.row.fixEdu"
                    >sku：
                    <span
                      v-for="(ii, iindex) in scope.row.ali.skuInfos"
                      :key="iindex"
                    >
                      <span
                        v-show="ii.specId == scope.row.tt.child[0].out_sku_id"
                        v-for="(i, index) in ii.attributes"
                        :key="index"
                      >
                        {{ i.attributeName }}：
                        {{ i.attributeValue }}
                      </span>
                    </span>
                  </el-link>
                  <el-row style="white-space: nowrap">
                    <el-select
                      v-model="scope.row.tt.child[0].out_sku_id"
                      placeholder="请选择"
                      v-show="scope.row.fixEdu"
                    >
                      <el-option
                        v-for="(item, index) in scope.row.ali.skuInfos"
                        :key="index"
                        :label="
                          item.attributes[0].attributeName +
                          ':' +
                          item.attributes[0].attributeValue +
                          (item.attributes.length > 1
                            ? item.attributes[1].attributeName +
                              ':' +
                              item.attributes[1].attributeValue
                            : '')
                        "
                        :value="item.specId"
                      >
                        <span v-for="(i, index) in item.attributes" :key="index"
                          >{{ i.attributeName }}:{{ i.attributeValue }}</span
                        >
                        <span>价格：{{ item.consignPrice }}</span>
                      </el-option>
                    </el-select>
                    <el-button
                      v-show="scope.row.fixEdu"
                      type="success"
                      icon="el-icon-check"
                      circle
                      @click="scope.row.fixEdu = !scope.row.fixEdu"
                    ></el-button>
                  </el-row>
                </el-badge>
              </el-row>
              <el-row style="border: 1px dashed #2aa1ff" title="更换">
                <el-badge value="更换" class="item" type="primary">
                  <el-link
                    :underline="false"
                    @click="scope.row.fixShop = !scope.row.fixShop"
                    v-show="!scope.row.fixShop"
                    >类别：{{ scope.row.ali.categoryName }}</el-link
                  >
                  <el-row style="white-space: nowrap">
                    <el-select
                      v-model="form.edu"
                      style
                      v-show="scope.row.fixShop"
                    >
                      <el-option
                        v-for="item in aliShop"
                        :key="item.value"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                    <el-button
                      v-show="scope.row.fixShop"
                      type="success"
                      icon="el-icon-check"
                      circle
                      @click="scope.row.fixShop = !scope.row.fixShop"
                    ></el-button>
                  </el-row>
                </el-badge>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="200">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.tt.child" :key="index">
            {{ item.post_addr.province.name }}- {{ item.post_addr.city.name }}-
            {{ item.post_addr.town.name }}- {{ item.post_addr.detail }} <br />
            手机号：{{ item.post_tel }}
            <br />
            收件人：{{ item.post_receiver }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="150">
        <template slot-scope="scope">
          ¥
          {{ scope.row.ali.referencePrice }}
        </template>
      </el-table-column>
      <el-table-column label="数量" width="200">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.tt.childNum"
            :min="1"
            :max="999"
            label="描述文字"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.ali.productID != null"
            @click="
              $router.push({
                path: `/1688/shop/detail/${scope.row.tt.child[0].out_product_id}`,
              })
            "
            type="text"
            size="small"
            >查看</el-button
          >
          <el-button
            v-if="scope.row.ali.productID != null"
            type="text"
            size="small"
            @click="previewOrder(scope)"
            >下单前预览</el-button
          >
          <!-- 绑定数据 -->
          <el-dialog
            title="建立绑定"
            :visible.sync="addBind"
            width="50%"
            :modal="false"
          >
            <el-row>
              <el-select
                v-model="offerId"
                clearable
                filterable
                placeholder="从商品库选取"
              >
                <el-option
                  v-for="item in 10"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-row>
            <el-row>
              <el-input
                placeholder="商品Id"
                type="number"
                v-model="offerId"
                clearable
              >
              </el-input>
            </el-row>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addBind = false">取 消</el-button>
              <el-button type="primary" @click="bindGoods(scope)"
                >绑定</el-button
              >
            </span>
          </el-dialog>

          <el-button
            v-if="scope.row.ali.productID == null"
            type="text"
            size="small"
            @click="bindGoodsIndex(scope.$index)"
            >建立临时绑定关系</el-button
          >
          <el-dialog
            title="订单预览"
            :visible.sync="dialogVisible"
            :modal="false"
            width="80%"
          >
            <div
              v-for="(item, index) in previewData.orderPreviewResuslt"
              :key="index"
            >
              <span>可用店铺级别优惠列表:</span><br />
              <ul v-for="(item2, index) in item.shopPromotionList" :key="index">
                <li>是否默认选中：{{ item2.selected ? "是" : "不是" }}</li>
                <li>优惠券名称：{{ item2.text }}</li>
                <li>优惠券描述：<span v-html="item2.desc"></span></li>
                <li>是否免邮：{{ item2.freePostage }}</li>
                <li>减去金额：{{ item2.discountFee / 100 }}</li>
              </ul>
              <br />
              <span
                >当前交易可以支持的交易方式列表。结果可以参照1688下单预览页面的交易方式：</span
              >
              <ul
                v-for="(item3, index3) in item.tradeModelList"
                :key="index3 + 10"
              >
                <li>交易描述：{{ item3.description }}</li>
                <li>交易方式名称：{{ item3.name }}</li>
                <li>是否支持：{{ item3.opSupport }}</li>
                <li>开放平台下单时候传入的tradeType：{{ item3.tradeType }}</li>
                <li>交易方式：{{ item3.tradeWay }}</li>
              </ul>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="dialogVisible = false"
                >确 定</el-button
              >
            </span>
          </el-dialog>
          <el-button
            v-if="scope.row.ali.productID != null"
            type="text"
            size="small"
            @click="cOrder(scope)"
            >下单</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="10"
      :total="total"
      @current-change="splitPage"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: "order",
  data() {
    return {
      bindIndex: 0,
      offerId: "",
      addBind: false,
      previewData: {},
      dialogVisible: false,
      num: 1,
      currentSku: [],
      total: 20,
      tableData: [],
      current: 1,
      form: {
        specId: "",
        accessToken: "",
        offerId: "",
      },
      aliEdu: [],
      aliShop: [],
      fixEdu: false,
      fixShop: false,
      formOffer: {
        accessToken: "",
        offerId: "",
      },
      param: {
        accessToken: "",
        addressParam: {
          fullName: "",
          mobile: "",
          phone: "",
          postCode: "000000",
          cityText: "",
          provinceText: "",
          areaText: "",
          townText: "",
          address: "",
          districtCode: "310107",
        },
        cargoParamList: {
          offerId: "",
          specId: "",
          quantity: 1,
        },
        message: "",
        outerOrderInfo: {
          mediaOrderId: 11,
          phone: "",
          offers: [
            {
              id: 607933520941,
              specId: "d1206cb7f04635fe7efcc15a3d2fc938",
              price: 12,
              num: 20,
            },
          ],
        },
      },
    };
  },
  methods: {
    bindGoodsIndex(index) {
      this.addBind = true;
      this.bindIndex = index;
    },
    async bindGoods(scope) {
      let _this = this;
      this.addBind = false;
      await this.$http
        .post(`/goods/detail`, { offerId: this.offerId })
        .then((res) => {
          let data = JSON.parse(res.data.message);
          if (data.success) {
            this.tableData[this.bindIndex].ali = data.productInfo;
          } else {
            console.log(dadatate);
            _this.$message({
              message: "绑定失败【" + data.errorMsg + "】",
              type: "warning",
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message({ message: "绑定失败" });
        });
    },
    async previewOrder(item) {
      let tt = item.row.tt;
      let ali = item.row.ali;
      if (tt.child[0].out_sku_id == null) {
        this.$message({ message: "请选择Sku信息", type: "warning" });
        return;
      }
      let addressParam = {
        addressId: 0,
        fullNameString: tt.postReceiver,
        mobile: tt.postTel,
        phone: tt.postTel,
        postCode: "000000",
        cityText: tt.cityName,
        provinceText: tt.provinceName,
        areaText: tt.townName,
        townText: tt.townName,
        address: tt.detail,
        districtCode: "",
      };
      let cargoParamList = [
        {
          offerId: tt.child[0].out_product_id,
          specId: tt.child[0].out_sku_id,
          quantity: tt.childNum,
        },
      ];
      let addressDetail =
        addressParam.provinceText +
        " " +
        addressParam.cityText +
        " " +
        addressParam.townText;
      await this.$http
        .post(`/ttOrder/get-address-code?address=${addressDetail}`)
        .then((res) => {
          let address = JSON.parse(res.data.message);
          addressParam.districtCode = address.result.addressCode;
          this.$http
            .post(
              `/ali-order/1688/check-library-total?cargoParamList=${JSON.stringify(
                cargoParamList
              )}&addressParam=${JSON.stringify(addressParam)}`
            )
            .then((res) => {
              let resu = JSON.parse(res.data.message);
              if (resu.success) {
                this.previewData = resu;
                this.dialogVisible = true;
              } else {
                this.this.$message({
                  message: "" + resu.errorMsg,
                  type: "warning",
                });
              }
            })
            .catch((err) => {
              //this.dialogVisible = false;
              this.$message({ message: "失败", type: "warning" });
            });
        });
    },
    setSku(index) {
      let ali = this.tableData[index].ali;
      let tt = this.tableData[index].tt;
      if (tt.child.out_product_id == 0) {
        this.currentSku.push(0);
      } else {
        ali.skuInfos.forEach((item, i) => {
          if (item.specId == tt.child[0].out_sku_id) {
            this.currentSku.push(i);
          }
        });
      }
    },
    splitPage(res) {
      this.tableData = [];
      this.form = {
        specId: "",
        accessToken: "",
        offerId: "",
      };
      this.formOffer = {
        accessToken: "",
        offerId: "",
      };
      this.getOrder(res);
    },
    handleClick(row) {
      console.log(row);
    },
    getAliEdu(shop) {},
    getShop(shop) {},
    getOrder(current = 1) {
      this.$http.get(`/ttOrder/get-order/${current}`).then((response) => {
        if (response.data.code == 403) {
          this.$message({
            message: "网络错误【" + response.data.message + "】",
            type: "warning",
          });
        } else {
          this.total = response.data.dataMap.data.total;
          let result = response.data.dataMap.data.records;
          let target = [];
          result.forEach((item) => {
            item["child"] = JSON.parse(item["child"]);
            let offerId = item.child[0].out_product_id;
            if (item.child[0].out_sku_id == "") {
              item.child[0].out_sku_id = 1;
            }
            this.$http
              .get(
                `/bind/get/goods-bind/${item.child[0].out_sku_id}/${offerId}`
              )
              .then((res) => {
                item.child[0].out_sku_id = res.data.dataMap.data.specId;
                this.form.offerId = offerId;
                let target1 = {
                  tt: item,
                  ali: {
                    referencePrice: 0,
                    image: {
                      images: [
                        "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1404104172,4258698811&fm=26&gp=0.jpg",
                      ],
                    },
                    subject: "没有建立绑定关系",
                    skuInfos: [
                      {
                        attributes: [
                          {
                            attributeName: "提示",
                            attributeValue: "没有建立绑定关系",
                          },
                        ],
                        specId: "0",
                      },
                    ],
                  },
                  fixEdu: false,
                  fixShop: false,
                };
                this.formOffer.offerId = offerId;
                if (offerId != 0) {
                  this.$http
                    .post(`/goods/detail`, this.formOffer)
                    .then((response) => {
                      let ali = JSON.parse(response.data.message).productInfo;
                      target1.ali = ali;
                    });
                }
                target.push(target1);
              })
              .catch((err) => {
                //this.$message({ message: "失败", type: "warning" });
              });
          });
          this.tableData = target;
          //this.$message({ message: "成功", type: "success" });
        }
      });
    },
    async cOrder(item) {
      this.dialogVisible = false;
      let param = this.param;
      let tt = this.tableData[item.$index].tt;
      let ali = this.tableData[item.$index].ali;

      param.addressParam.fullName = tt.postReceiver;
      param.addressParam.mobile = tt.postTel;
      param.addressParam.phone = tt.postTel;
      param.addressParam.cityText = tt.cityName;
      param.addressParam.provinceText = tt.provinceName;
      param.addressParam.areaText = "";
      param.addressParam.townText = tt.townName;
      param.addressParam.address = tt.detail;
      param.cargoParamList.offerId = ali.productID;
      param.cargoParamList.specId = tt.child[0].out_sku_id;
      param.outerOrderInfo.offers[0].specId = tt.child[0].out_sku_id;
      param.outerOrderInfo.offers[0].id = ali.productID;
      param.outerOrderInfo.offers[0].num = tt.childNum;
      param.outerOrderInfo.offers[0].price = tt.child[0].combo_amount;
      param.cargoParamList.quantity = tt.childNum;
      param.outerOrderInfo.phone = tt.child[0].post_tel;
      let addressDetail =
        param.addressParam.provinceText +
        " " +
        param.addressParam.cityText +
        " " +
        param.addressParam.townText;
      this.$http
        .post(`/ttOrder/get-address-code?address=${addressDetail}`)
        .then((res) => {
          let address = JSON.parse(res.data.message);
          param.addressParam.districtCode = address.result.addressCode;
          //param.cargoParamList.specId = "d1206cb7f04635fe7efcc15a3d2fc938";
          Object.keys(param).forEach((key, index) => {
            param[key] = JSON.stringify(param[key]);
          });
          param.accessToken = "";
          console.log(param);
          this.$http
            .post(`/ttOrder/add-ali-order`, param)
            .then((response) => {
              let r = JSON.parse(response.data.message);
              console.log(r);
              if (r.success) {
                let logistics = {
                  ttOrderId: item.row.tt.orderId,
                  aliOrderId: r.result.orderId,
                };
                this.$http
                  .put(`/ttOrder/fix-tt-order-status/${item.row.tt.id}`)
                  .then((res) => {
                    this.$http
                      .post(`/aliOrderLogistics/add-logistics`, logistics)
                      .then((res) => {
                        // this.$message({
                        //   message: "创建成功" + err.result,
                        //   type: "success",
                        // });
                        this.$router.push({ path: `/1688/order/${1}` });
                      });
                  })
                  .catch((err) => {
                    this.$message({
                      message: "修改状态失败" + err.result,
                      type: "warning",
                    });
                  });
              } else {
                this.$message({
                  message: "" + r.errorMsg,
                  type: "warning",
                });
              }
              this.param = {
                accessToken: "",
                addressParam: {
                  fullName: "",
                  mobile: "",
                  phone: "",
                  postCode: "000000",
                  cityText: "",
                  provinceText: "",
                  areaText: "",
                  townText: "",
                  address: "",
                  districtCode: "310107",
                },
                cargoParamList: {
                  offerId: "",
                  specId: "",
                  quantity: "1",
                },
                message: "",
                outerOrderInfo: {
                  mediaOrderId: 11,
                  phone: "",
                  offers: [
                    {
                      id: 607933520941,
                      specId: "d1206cb7f04635fe7efcc15a3d2fc938",
                      price: 12,
                      num: 1,
                    },
                  ],
                },
              };
            })
            .catch((err) => {
              console.log(err);
              this.$message({ message: "创建失败", type: "warning" });
            });
        })
        .catch((err) => {
          this.param = {
            accessToken: "",
            addressParam: {
              fullName: "",
              mobile: "",
              phone: "",
              postCode: "000000",
              cityText: "",
              provinceText: "",
              areaText: "",
              townText: "",
              address: "",
              districtCode: "310107",
            },
            cargoParamList: {
              offerId: "",
              specId: "",
              quantity: "1",
            },
            message: "",
            outerOrderInfo: {
              mediaOrderId: 11,
              phone: "",
              offers: [
                {
                  id: 607933520941,
                  specId: "d1206cb7f04635fe7efcc15a3d2fc938",
                  price: 12,
                  num: 1,
                },
              ],
            },
          };
          this.$message({ message: "创建失败", type: "warning" });
        });
    },
  },
  created() {
    this.getOrder();
  },
};
</script>

<style>
.el-scrollbar_wrap {
  overflow: scroll;
  height: 100%;
}
.page-component_scroll {
  height: 500px;
}
</style>
